/**
 * Created by leiqr on 2015/9/23.
 */
define(function (require, exports, module) {
    require("angular-ui");
    require("angular-route");
    var moment = require("moment");
    require("permission");
    var angular = require("angular");
    require("angular-interceptor");
    require("pagination");
    var util = require("util");
    require('/static_public/js/angular_directive/projectTreeSelector.js');


    var urlPrefix = window['G_CONFIG']['api_prefix'];


    angular.module('app', ['ngRoute', 'ngInterceptor', 'ngUI','projectTreeSelector'])
        .factory('httpPost', ['$http', function ($http) {
            return function (url, data) {
                if (!data) {
                    data = {};
                }
                data = $.extend(data, {"USE_FORM_DATA": false});
                return $http.post(url, data);
            }
        }])
        .service('cstServiceList', ['$q', 'httpPost', function ($q, httpPost) {
            var service = {
                getProjectList: function () {
                    var deferred = $q.defer();
                    httpPost(urlPrefix + 'wcb/project/list/&flag=0&jointparent=1')
                        .success(function (res) {
                            if (res.retCode == 0) {
                                deferred.resolve(res.data);
                            }
                        });
                    return deferred.promise;
                },
                getCstList: function (queryData) {
                    var deferred = $q.defer();
                    httpPost(urlPrefix + 'wcb/call-manage/get-call-list&' + $.param(queryData))
                        .success(function (res) {
                            if (res.retCode == 0) {
                                deferred.resolve(res);
                            }
                        });
                    return deferred.promise;
                }
            };
            return service;
        }])
        .filter('crmTagsFormat',function(){
            return function(inputArray,len){
                var array = [];
                len = len || inputArray.length;
               array = _.first(inputArray,Math.min(inputArray.length,len));
               return  _.map(array,function(item){
                    return item[0]+' : '+item[1].join();
                });
            }
        })
        .controller('MainController', ['$rootScope', '$scope', '$location', '$route', '$routeParams', 'cstServiceList',
            function ($rootScope, $scope, $location, $route, $routeParams, cstServiceList) {

                cstServiceList.getProjectList().then(function(data){
                    $scope.projectList = data;
                });

                $scope.filter = {
                    callTime: 'today',
                    callStatus: '',
                    startDate: null,
                    endDate: null,
                    pageSize: 10
                };


                $scope.pageIndex = 1;

                $scope.getCstList = function () {

                    cstServiceList.getCstList({
                        pageIndex: 0,
                        pageSize: $scope.filter.pageSize,
                        callStatus: '',
                        beginTime: $scope.filter.callTime == 'all' ? '' : $scope.filter.startDate,
                        endTime: $scope.filter.callTime == 'all' ? '' : $scope.filter.endDate,
                        projId:$scope.curProjectId
                    }).then(function (res) {
                        _.each(res.data,function(item){
                            var crmTagsObj;
                            if(typeof item.crm_tags=='string'){
                                crmTagsObj = JSON.parse(item.crm_tags);
                            }else{
                                crmTagsObj = item.crm_tags;
                            }
                            item.crm_tags = _.pairs(crmTagsObj);
                        });
                        $scope.tableList = res.data;
                        $scope.total = res.total;
                    }).finally(function () {

                    });
                };
                //计算时段
                $scope.setDateMode = function (mode) {
                    var start, end;
                    var today = moment();

                    switch (mode) {
                        case 'year':
                            start = moment().startOf('year');
                            end = moment(start).add(1, 'years');
                            if (end.isAfter(today)) {
                                end = today;
                            }
                            break;

                        case 'quarter':
                            start = moment().startOf('quarter');
                            end = moment(start).add(1, 'quarters');
                            if (end.isAfter(today)) {
                                end = today;
                            }
                            break;

                        case 'month':
                            start = moment().startOf('month');
                            end = moment(start).add(1, 'months');
                            if (end.isAfter(today)) {
                                end = today;
                            }
                            break;

                        case 'week':
                            start = moment().startOf('week');
                            end = moment(start).add(1, 'weeks');
                            if (end.isAfter(today)) {
                                end = today;
                            }
                            break;
                        case 'today':
                            start = moment().startOf('day');
                            end = moment(start).add(1, 'days');
                            if (end.isAfter(today)) {
                                end = today;
                            }
                            break;
                        case 'yesterday':
                            start = moment().subtract(1, 'day');
                            end = start;
                            if (end.isAfter(today)) {
                                end = today;
                            }
                            break;
                        case 'all':
                            start = null;
                            end = null;
                            break;

                        case 'custom':
                            return;
                    }

                    if (start) {
                        $scope.filter.startDate = start.format('YYYY-MM-DD')+' 00:00:00';
                    } else {
                        $scope.filter.startDate = '';
                    }
                    if (end) {
                        $scope.filter.endDate = end.format('YYYY-MM-DD')+' 23:59:59';
                    } else {
                        $scope.filter.endDate = '';
                    }
                };

                //搜索
                $scope.getSearchData = function () {
                    $scope.pageIndex = 1;
                    if($scope.filter.phone){
                        $scope.queryParams.phone = $scope.filter.phone;
                        cstServiceList.getCstList({
                            pageIndex: 0,
                            pageSize: $scope.filter.pageSize,
                            phone: $scope.filter.phone,
                            projId:$scope.curProjectId
                        }).then(function (res) {
                            _.each(res.data,function(item){
                                var crmTagsObj;
                                if(typeof item.crm_tags=='string'){
                                    crmTagsObj = JSON.parse(item.crm_tags);
                                }else{
                                    crmTagsObj = item.crm_tags;
                                }
                                item.crm_tags = _.pairs(crmTagsObj);
                            });
                            $scope.tableList = res.data;
                            $scope.total = res.total;
                        }).finally(function () {

                        });
                    }else{
                        $scope.filter.callTime= 'today';
                        $scope.setDateMode('today');
                        $scope.filter.callStatus= '';
                        $scope.getFilterData();
                    }

                };


                //查询
                $scope.getFilterData = function (pageIndex) {
                    if($scope.filter.callTime == 'custom'&& !$scope.filter.startDate && !$scope.filter.endDate){
                        util.alert('请选择自定义时段！');
                        return;
                    }
                    var params = {};
                    $scope.pageIndex = pageIndex !== undefined ? pageIndex : 1;
                    if(pageIndex !== undefined){//分页获取数据
                        if($scope.queryParams.phone){
                            params = {pageIndex:pageIndex-1,phone :$scope.queryParams.phone,projId:$scope.curProjectId,pageSize:$scope.filter.pageSize};
                        }else{
                            params = $.extend($scope.queryParams,{pageIndex:pageIndex-1,pageSize:$scope.filter.pageSize});
                        }

                    }else{//查询
                        $scope.filter.phone = '';
                        params = {
                            pageIndex: pageIndex !== undefined ? pageIndex - 1 : $scope.pageIndex-1,
                            pageSize: $scope.filter.pageSize,
                            callStatus: $scope.filter.callStatus,
                            beginTime: $scope.filter.callTime == 'all' ? '' : $scope.filter.startDate,
                            endTime: $scope.filter.callTime == 'all' ? '' : $scope.filter.endDate,
                            phone: $scope.filter.phone,
                            projId:$scope.curProjectId
                        };
                        $scope.queryParams = params;

                    }
                    cstServiceList.getCstList(params).then(function (res) {
                        _.each(res.data,function(item){
                            var crmTagsObj;
                            if(typeof item.crm_tags=='string'){
                                crmTagsObj = JSON.parse(item.crm_tags);
                            }else{
                                crmTagsObj = item.crm_tags;
                            }
                            item.crm_tags = _.pairs(crmTagsObj);
                        });
                        $scope.tableList = res.data;
                        $scope.total = res.total;
                    }).finally(function () {

                    });
                };


                $scope.exportData = function (e) {
                    var params = {
                        callStatus: $scope.queryParams.callStatus,
                        beginTime: $scope.queryParams.beginTime,
                        endTime: $scope.queryParams.endTime,
                        phone: $scope.queryParams.phone,
                        projId: $scope.curProjectId
                    };
                    $(e.target).attr('href', urlPrefix + "wcb/call-manage/export&" + $.param(params));
                };


                function update(curProjectId) {
                    $scope.getCstList();
                    $scope.queryParams = {
                        pageIndex: 0,
                        pageSize: $scope.filter.pageSize,
                        callStatus: '',
                        beginTime: $scope.filter.callTime == 'all' ? '' : $scope.filter.startDate,
                        endTime: $scope.filter.callTime == 'all' ? '' : $scope.filter.endDate,
                        projId:$scope.curProjectId
                    };
                }

                $scope.$watch('curProjectId', function (newValue, oldValue) {
                    if (newValue !== oldValue) {
                        update(newValue);
                    }
                });

                $scope.$watch('filter.callTime', function (newValue, oldValue) {
                    if (newValue !== oldValue) {
                        $scope.setDateMode(newValue);
                    }
                });

                $scope.setDateMode('today');


            }
        ]);

    angular.bootstrap(document, ['app']);
});
